import sys
import os
sys.path.append(os.path.abspath(os.path.dirname(__file__)) + "/..")
from stock.simulatestock import *
from utils.smtp.smtp import *
from utils.utils import *
import time


def macd_valid(df):
    if len(df["diff"]) < 2:
        return False
    diff = float(df["diff"][-1])
    dea = float(df["dea"][-1])
    if diff < 0 or dea < 0 or diff < dea:
        return False

    return True

def macd_sel_proc(code, sarray):
    #先取季线，再取月线，再取周线，再取日线
    day = 240
    week = day * 7
    month = day * 30
    quarter = month * 3
    # print("goto check ", code)
    kq = SimulateStock(code, quarter, 100)
    
    if kq.GetMacdDf() == False:
        return
    # print("quarter-df", kq.df)
    if macd_valid(kq.df) == False:
        return
    km = SimulateStock(code, month, 100)
    if km.GetMacdDf() == False:
        return
    # print("month-df", km.df)
    if macd_valid(km.df) == False:
        return        
    kw = SimulateStock(code, week, 100)
    if kw.GetMacdDf() == False:
        return
    # print("week-df", kw.df)
    if macd_valid(kw.df) == False:
        return
    kday = SimulateStock(code, day, 100)
    if kday.GetMacdDf() == False:
        return
    # print("day-df", kday.df)
    if macd_valid(kday.df) == False:
        return
    print("found the valid code ", code)
    sarray.append(code)
    

def macd_select():
    # if work_time_check() == False:
    #     # print("err time")
    #     return
    print("*********************start**************************************")
    select_array = []
    codes = get_codes()
    # codes = ["sz002191"]
    for code in codes:
        macd_sel_proc(code, select_array)

    str = "%s"%(get_local_time("%Y-%m-%d %H:%M:%S "))
    for stat in select_array:
        str += "%s "%(stat["code"])
    smtp = Smtp()
    print(str)
    smtp.Send(str)

def test():
    for i in range(7200*3, 7200*10):
        str = "https://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol=%s&scale=%d&ma=no&datalen=%d"%("sz002191", i, 10)
        # print("url", str)
        a = get_url_data(str)
        if a != None:
            print(i)
            print(a)

if __name__ == "__main__":
    test()
    # macd_select()
    # while True:
    #     try:
    #         macd_select()
    #     except :
    #         print("catch err*****************")
    #     else:
    #         pass
    #     time.sleep(10)